package tasks;

import java.io.IOException;
import java.io.InputStream;

import tools.Format;

import core.Executor;
import core.Message;
import core.Peer;
import core.TorrentManager;

public class ReadHandshake implements Runnable {
	private Peer peer;


	public ReadHandshake(Peer peer) {
		this.peer = peer;        
	}

	@Override
	public void run() {
		try {
			if(this.readHanshake()) {
				Executor.getThreadPool().execute(new SendHandshake(this.peer,this.peer.getInfoHash()));
				Executor.getThreadPool().execute(new SendMessage(new Message(5, TorrentManager.getInstance().getTorrent(this.peer.getInfoHash()).getBitfield(), this.peer.getOutput())));
				Executor.getThreadPool().execute(new SendMessage(new Message(1,this.peer.getOutput())));
				Executor.getThreadPool().execute(new SendMessage(new Message(2,this.peer.getOutput())));
				Executor.getThreadPool().execute(new ReadMessage(this.peer,TorrentManager.getInstance().getTorrent(this.peer.getInfoHash())));
				TorrentManager.getInstance().addPeerByTorrent(this.peer.getInfoHash(),this.peer);

			} else {
				this.peer.close();
			}
		} catch (IOException e) {
			System.out.println("ReadHandshake|IOException: "+e);
		} catch (Exception e) {
			System.out.println("ReadHandshake|Exception: "+e);
		}
	}

	public boolean readHanshake() throws IOException {
		int length = 0;
		byte[] info_hash = new byte[20];
		byte[] bytes = new byte[1];             

		InputStream input = this.peer.getInput();

     
		if (input.read(bytes) == -1) {
			return false;
		}

		int i1 = new Byte(bytes[0]).intValue();

		if(i1 > 0) {
			bytes = new byte[i1];
			length = i1;
		} else {
			return false;
		}

		if (input.read(bytes) == -1) {
			return false;
		}



		String software_id = new String(bytes);
		if (!software_id.equals("BitTorrent protocol")) {
			return false;            
		}

		bytes = new byte[8];
		if (input.read(bytes) == -1) {
			return false;
		}

		bytes = new byte[20];
		if (input.read(bytes) == -1) {
			return false;
		}
		info_hash = bytes;


		if(TorrentManager.getInstance().getTorrent(info_hash) == null) {   
			return false;
		}
		this.peer.setInfoHash(info_hash);


		bytes = new byte[20];
		if (input.read(bytes) == -1) {
			return false;
		}

		this.peer.setPeerId(new String(bytes));

		return true;
	}

}
